package com.bw.module_home.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bw.lib_common.arout.ARouterPath
import com.bw.lib_mvicore.ui.BaseMviFragment
import com.bw.module_home.R
import com.bw.module_home.common.RedPacketEnum
import com.bw.module_home.common.RedPacketEvent
import com.bw.module_home.databinding.HomeFragmentSimpleTypeBinding
import com.bw.module_home.intent.FocusIntent
import com.bw.module_home.intent.SimpleVideoIntent
import com.bw.module_home.state.FocusState
import com.bw.module_home.state.SimpleVideoState
import com.bw.module_home.ui.adapter.SimpleRecycleViewAdapter
import com.bw.module_home.viewmodel.FocusViewModel
import com.bw.module_home.viewmodel.SimpleVideoViewModel
import com.ethanhua.skeleton.RecyclerViewSkeletonScreen
import com.ethanhua.skeleton.Skeleton
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

class SimpleTypeFragment : BaseMviFragment() {
    private lateinit var simpleVideoViewModel: SimpleVideoViewModel
    private lateinit var focusViewModel: FocusViewModel
    private lateinit var binding: HomeFragmentSimpleTypeBinding
    private lateinit var simpleRecyclerViewAdapter: SimpleRecycleViewAdapter
    private lateinit var skeletonScreen: RecyclerViewSkeletonScreen

    private var rvIsScoll = false

    override fun generateViewModel() {
        simpleVideoViewModel = ViewModelProvider(this)[SimpleVideoViewModel::class.java]
        focusViewModel = ViewModelProvider(this)[FocusViewModel::class.java]
    }

    override fun initView() {
        super.initView()
        initRecyclerView()
    }

    private fun initRecyclerView() {
        binding.let {
            simpleRecyclerViewAdapter = SimpleRecycleViewAdapter()
            val layoutManager = LinearLayoutManager(requireContext())
            layoutManager.orientation = RecyclerView.VERTICAL
            it.rvFragmentSimple?.layoutManager = layoutManager
            it.rvFragmentSimple?.adapter = simpleRecyclerViewAdapter
            it.rvFragmentSimple.setHasFixedSize(true)

            skeletonScreen = Skeleton.bind(it.rvFragmentSimple)
                .adapter(simpleRecyclerViewAdapter)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(3000)
                .color(R.color.teal_200)
                .count(5)
                .load(R.layout.home_item_simple_info_skeleton)
                .show()

        }
    }

    override fun initEvent() {
        /**
         * 上拉刷新
         */
        binding?.srlFragmentSimple?.setOnRefreshListener{
            page = 0
            getSimpleVideo()
            it.finishRefresh()
        }
        /**
         * 下拉加载
         */
        binding?.srlFragmentSimple?.setOnLoadMoreListener {
            page++
            getSimpleVideo()
            it.finishLoadMore()
        }
        //滑动列表监听
        binding.rvFragmentSimple.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when(newState){
                    RecyclerView.SCROLL_STATE_IDLE -> {//停止滑动
                        //恢复加载图片
                        if (rvIsScoll){
                            Glide.with(requireContext()).resumeRequests()
                        }
                        rvIsScoll = false
                        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING ->{//滑动
                        //停止加载图片
                        rvIsScoll = true
                        Glide.with(requireContext()).pauseAllRequests()
                        startPlayAnim();
                    }
                    RecyclerView.SCROLL_STATE_SETTLING->{//滑动
                        //停止加载图片
                        rvIsScoll = true
                        Glide.with(requireContext()).pauseRequests()
                        startPlayAnim();
                    }
                }
            }
        })

        //item点击
        simpleRecyclerViewAdapter.playListener = {
            showMsg("你点击了播放按钮: ${it.description}")
            ARouter.getInstance().build(ARouterPath.PAGE_HOME_DETAIL).withParcelable("data",it).navigation()
        }

        //item点击关注按钮跳转
        simpleRecyclerViewAdapter.focusListener = { entity, position ->
            if (!entity.fouces) {
                //去关注：更新UI（局部增量刷新）----》发起网络请求---》成功/失败（变回来）
                entity.fouces = true
                simpleRecyclerViewAdapter.updateItem(
                    entity,
                    position,
                    SimpleRecycleViewAdapter.PAYLOAD_FOCUS
                )
                //发起网络请求
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED) {
                        focusViewModel.intents.send(FocusIntent.Focus(173, entity.id, position))
                    }
                }
            }
        }

        simpleRecyclerViewAdapter.likeListener = {entity,position->
            if(entity.like){//取消点赞
                entity.like = false
                simpleRecyclerViewAdapter.updateItem(entity,position,SimpleRecycleViewAdapter.PAYLOAD_LIKE)

            }else{
                entity.like = true
                simpleRecyclerViewAdapter.updateItem(entity,position,SimpleRecycleViewAdapter.PAYLOAD_LIKE)

            }

        }

    }

    /**
     * 是否已开始执行进度动画
     */
    private var isStart:Boolean=false
    private fun startPlayAnim() {
        if(isStart){
            EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME))
        }else{
            EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.INIT))
            isStart = true

        }
    }

    var page: Int = 0
    val pagesize: Int = 10
    var channelId: String = ""
    override fun lazyLoad() {
        //获得channelId
        channelId = arguments?.getString("id").toString()

        getSimpleVideo()
    }
    /**
     * 发送根据ChannelId获取Simple视频信息意图
     */
    private fun getSimpleVideo() {
        //根据id获得视频数据
        lifecycleScope.launch{
            simpleVideoViewModel.intents.send(SimpleVideoIntent.GetSimpleVideo(channelId,page,pagesize))
        }
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = HomeFragmentSimpleTypeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                simpleVideoViewModel.state.collect{
                    when(it) {
                        is SimpleVideoState.SimpleVideos -> {
                            simpleRecyclerViewAdapter.addList(it.list)
                            skeletonScreen.hide()
                        }
                        is SimpleVideoState.Failed -> {
                            showMsg("视频数据失败${it.error}")
                        }
                        is SimpleVideoState.Init -> {

                        }
                        is SimpleVideoState.RecommendSimpleVideos -> {
                            showMsg("推荐数据${it.list}")
                        }
                        is SimpleVideoState.RecommendFailed -> {
                            showMsg("推荐数据失败${it.error}")
                        }
                    }
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                focusViewModel.state.collect{
                    when(it){
                        is FocusState.FocuseSuccess-> {
                            showMsg("关注成功")
                        }
                        is FocusState.FocuseFailed-> {
                            showMsg("关注失败")
                            val simpleVideoEntity = simpleRecyclerViewAdapter.getDataByPosition(it.position)
                            simpleVideoEntity?.let {entity ->
                                simpleVideoEntity.fouces = false
                                simpleRecyclerViewAdapter.updateItem(entity,it.position,SimpleRecycleViewAdapter.PAYLOAD_FOCUS)
                            }
                        }
                        is FocusState.Init-> {

                        }
                    }
                }
            }
        }
    }

}